<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.username"
          placeholder="请输入用户名查询"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
        <el-button type="primary" :icon="Plus" @click="openDialog('add')"
          >新增</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column width="100" align="center" label="序号">
          <template v-slot="scope">
            {{ indexMethod(scope.$index, query.pageIndex, query.pageSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="orgName" label="区域名称"></el-table-column>
        <el-table-column prop="username" label="用户名">
          <!-- <template #default="scope">￥{{ scope.row.money }}</template> -->
        </el-table-column>
        <!-- <el-table-column prop="password" label="密码"></el-table-column> -->
        <el-table-column
          prop="email"
          label="邮箱"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button
              text
              :icon="Edit"
              @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button text :icon="EditPen" @click="resetPasswordFn(scope.row)">
              重置密码
            </el-button>
            <el-button
              text
              :icon="Delete"
              class="red"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      v-model="visible"
      width="30%"
      style="z-index: 900"
    >
      <el-form label-width="120px" ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item
          prop="password"
          label="密码"
          v-if="dialogTitle === '新增用户'"
        >
          <el-input v-model="form.password" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="form.mobile" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item prop="orgId" label="组织区域">
          <el-select
            v-model="form.orgId"
            class="m-2"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in orgList"
              :key="item.orgId"
              :label="item.name"
              :value="item.orgId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm(formRef)"
            :loading="saveLoading"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="重置密码"
      v-model="passwordVisible"
      width="30%"
      style="z-index: 900"
    >
      <el-form
        label-width="120px"
        ref="formRef2"
        :model="passwordForm"
        :rules="rules2"
      >
        <el-form-item prop="username" label="用户名">
          <el-input
            v-model="passwordForm.username"
            placeholder="请输入"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item prop="oldPassword" label="旧密码">
          <el-input
            v-model="passwordForm.oldPassword"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" label="新密码">
          <el-input
            v-model="passwordForm.password"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password2" label="再次输入密码">
          <el-input
            v-model="passwordForm.password2"
            type="password"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm2(formRef2)"
            :loading="passwordLoading"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Search, Plus, EditPen } from "@element-plus/icons-vue";
import {
  userList,
  addUser,
  delUser,
  editUser,
  orgList2,
  resetPassword,
} from "../../../api/index";
import { indexMethod } from "../../../utils/tools";
import type { FormInstance, FormRules } from "element-plus";

interface TableItem {
  id: number;
  name: string;
  money: string;
  state: string;
  date: string;
  address: string;
}

const query = reactive({
  username: "",
  pageIndex: 1,
  pageSize: 10,
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
  userList({
    pageNumber: query.pageIndex,
    pageSize: query.pageSize,
    username: query.username,
  }).then((res: any) => {
    tableData.value = res.rows;
    pageTotal.value = res.total || 0;
  });
};
getData();

// 获取组织区域
const orgList: any = ref([]);
const getOrgList = () => {
  orgList2().then((res: any) => {
    orgList.value = res || [];
  });
};
getOrgList();

// 查询操作
const handleSearch = () => {
  query.pageIndex = 1;
  getData();
};
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getData();
};

// 删除操作
const handleDelete = (data: any) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      delUser([data.userId]).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success("删除成功！");
          getData();
        } else {
          ElMessage.error(res.msg);
        }
      });
    })
    .catch(() => {});
};

// 新增用户
const dialogTitle = ref("");
const openDialog = (type: any) => {
  visible.value = true;
  form.username = "";
  form.password = "";
  form.email = "";
  form.mobile = "";
  form.orgName = "";
  form.orgId = "";
  dialogTitle.value = "新增用户";
};

// 表格编辑时弹窗和保存
const visible = ref(false);
const orgVisible = ref(false);
const formRef = ref<FormInstance>();
const rowData = ref({});
let form = reactive({
  username: "",
  password: "",
  password2: "",
  email: "",
  mobile: "",
  orgName: "",
  orgId: "",
});
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  mobile: [{ required: true, message: "请输入电话号码", trigger: "blur" }],
  orgId: [{ required: true, message: "请选择组织区域", trigger: "blur" }],
});
const handleEdit = (index: number, row: any) => {
  form.username = row.username;
  form.password = row.password;
  form.email = row.email;
  form.mobile = row.mobile;
  form.orgName = row.orgName;
  form.orgId = row.orgId;
  dialogTitle.value = "编辑用户";
  rowData.value = row;
  visible.value = true;
};
const saveLoading = ref(false);
const saveUserFn = () => {
  saveLoading.value = true;
  if (dialogTitle.value === "新增用户") {
    addUser({
      username: form.username,
      password: form.password,
      email: form.email,
      mobile: form.mobile,
      orgName: form.orgName,
      orgId: form.orgId,
    }).then((res: any) => {
      saveLoading.value = false;
      if (res.code === 200) {
        visible.value = false;
        ElMessage.success("新增成功！");
        getData();
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    editUser({
      ...rowData.value,
      username: form.username,
      password: form.password,
      email: form.email,
      mobile: form.mobile,
      orgName: form.orgName,
      orgId: form.orgId,
    }).then((res: any) => {
      saveLoading.value = false;
      if (res.code === 200) {
        ElMessage.success("编辑成功！");
        visible.value = false;
        getData();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (valid) {
      saveUserFn();
    } else {
      return false;
    }
  });
};

const passwordVisible = ref(false);
const passwordLoading = ref(false);
const formRef2 = ref<FormInstance>();
const passwordForm = reactive({
  username: "",
  userId: "",
  oldPassword: "",
  password: "",
  password2: "",
});
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== passwordForm.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};
const rules2 = reactive<FormRules>({
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  password: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  password2: [{ required: true, validator: validatePass, trigger: "blur" }],
});
const resetPasswordFn = (row: any) => {
  passwordVisible.value = true;
  passwordForm.username = row.username;
  passwordForm.userId = row.userId;
  passwordForm.oldPassword = row.oldPassword;
  passwordForm.password = row.password;
  passwordForm.password2 = row.password2;
};
const savePassword = () => {
  passwordLoading.value = true;
  resetPassword({
    username: passwordForm.username,
    userId: passwordForm.userId,
    oldPassword: passwordForm.oldPassword,
    password: passwordForm.password,
  }).then((res: any) => {
    passwordLoading.value = false;
    if (res.code === 200) {
      passwordVisible.value = false;
      ElMessage.success("重置密码成功！");
      getData();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const submitForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (valid) {
      savePassword();
    } else {
      return false;
    }
  });
};
</script>
<style scoped lang="less">
@import "./index.less";
</style>
